package com.example.mvplibrary.mvplibrary.adapter;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mvplibrary.mvplibrary.model.BaseModel;

import java.util.List;

public abstract class ReuseAdapter<D extends BaseModel> extends RecyclerView.Adapter<ReuseAdapter.ViewHolder> {

    private List<D> dataList;

    public ReuseAdapter(List<D> dataList) {
        this.dataList = dataList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(createLayoutId(), parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    protected abstract int createLayoutId();

    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        createHolder(holder,dataList.get(position));
    }

    protected abstract void createHolder(ViewHolder holder, D d);

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private View rootView;
        private SparseArray<View> views=new SparseArray<>();

        public ViewHolder(View itemView) {
            super(itemView);
        }

        public <T extends View> T get(int id){
            T view=(T)views.get(id);
            if(view==null){
                view=(T)rootView.findViewById(id);
                views.put(id,view);
            }
            return view;
        }
    }
}
